package net.pws.oos.biz.service.impl;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.pws.common.domain.BusinessException;
import net.pws.common.persistence.EntityManager;
import net.pws.oos.biz.BizException;
import net.pws.oos.biz.model.Indicator;
import net.pws.oos.biz.model.IndicatorTemplate;
import net.pws.oos.biz.model.IndicatorTemplateDetail;
import net.pws.oos.biz.service.IndicatorTemplateService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service(value = "indicatorTemplateService")
@Transactional
public class DefaultIndicatorTemplateManageService implements IndicatorTemplateService {

	@Autowired
	private EntityManager entityManager;


	public IndicatorTemplate saveIndicatorTemplate(IndicatorTemplate indicatorTemplate) {
		if (StringUtils.isEmpty(indicatorTemplate.getId())) {

			int count = ((Number) entityManager.findUnique(
					"select count(u.id) from IndicatorTemplate u where u.deleted = false and u.name = ?",
					new Object[] { indicatorTemplate.getName()})).intValue();
			if (count > 0) {
				throw new BizException(MessageFormat.format("名称[{0}]重复", indicatorTemplate.getName()));
			}
		} else {
			int count = ((Number) entityManager
					.findUnique(
							"select count(u.id) from IndicatorTemplate u where u.name = ? and u.id != ?",
							new Object[] { indicatorTemplate.getName(),
									indicatorTemplate.getId() })).intValue();
			if (count > 0) {
				throw new BizException(MessageFormat.format("名称[{0}]重复",
						indicatorTemplate.getName()));
			}
		}

		entityManager.persist(indicatorTemplate);
		return indicatorTemplate;
	}

	public void deleteIndicatorTemplate(String id) {
		IndicatorTemplate indicatorTemplate = entityManager.find(IndicatorTemplate.class, id);
		if (null == indicatorTemplate) {
			return;
		}

		String name = indicatorTemplate.getName();
		if (name.length() > 46) {
			name = name.substring(0, 46);
		}
		indicatorTemplate.setName(name + "|已删除");
		indicatorTemplate.setDeleted(Boolean.TRUE);
				
		entityManager.persist(indicatorTemplate);
	}

	@Override
	public List saveTemplateDetail(String templateId, List<Map> templateDetails) {
		List result = new ArrayList();
		IndicatorTemplate template = entityManager.getReference(IndicatorTemplate.class, templateId);
		if(null == template){
			throw new BusinessException("无效的id");
		}
		
		List<String> indicatorIds = new ArrayList<String>();
		for (Iterator<Map> iterator = templateDetails.iterator(); iterator.hasNext();) {
			Map templateDetail = iterator.next();
			String indicatorId = (String) templateDetail.get("id");
			if (StringUtils.isNotEmpty(indicatorId)) {
				indicatorIds.add("'"+indicatorId+"'");
			}
		}
		if(!indicatorIds.isEmpty()){
			String indicatorIdsStr = StringUtils.join(indicatorIds.toArray(),",");
			entityManager.execute(String.format("delete IndicatorTemplateDetail where template.id=? and (indicator.id not in (%1$s) and indicator.id in (select o.id from Indicator o where o.parent.id not in (%1$s) and o.parent.parent.id not in (%1$s)))", indicatorIdsStr), new String[]{ templateId });
		}
		
		String findDetailHql = "select d.id from IndicatorTemplateDetail d where d.template.id=? and d.indicator.id = ?";
		for (Iterator<Map> iterator = templateDetails.iterator(); iterator.hasNext();) {
			Map templateDetail = iterator.next();
			String indicatorId = (String) templateDetail.get("id");
			String detailId;
			int depth = (Integer) templateDetail.get("depth");
			String findHql = null;
			switch (depth) {
			case 0:
				findHql = "select o.id from Indicator o where o.depth = 3 and o.parent.parent.parent.id = ?";
				indicatorId = "0";
				break;
			case 1:
				findHql = "select o.id from Indicator o where o.depth = 3 and o.parent.parent.id = ?";
				break;
			case 2:
				findHql = "select o.id from Indicator o where o.depth = 3 and o.parent.id = ?";
				break;
			case 3:
				findHql = "select o.id from Indicator o where o.depth = 3 and o.id = ?";
				break;
			}
			@SuppressWarnings("unchecked")
			List<String> indicatorList = entityManager.findList(findHql, new String[]{indicatorId});
			for (Iterator<String> it = indicatorList.iterator(); it.hasNext();) {
				indicatorId = it.next();
				detailId = (String) entityManager.findFirst(findDetailHql, new String[]{templateId, indicatorId});
				Map item = new HashMap();
				item.put("id", indicatorId);
				if(StringUtils.isNotEmpty(detailId)){
					item.put("detailId", detailId);
				}else{
					IndicatorTemplateDetail detail = new IndicatorTemplateDetail();
					detail.setTemplate(template);
					Indicator indicator = entityManager.getReference(Indicator.class, indicatorId);
					detail.setIndicator(indicator);
					entityManager.persist(detail);
					item.put("detailId", detail.getId());
				}
	
				result.add(item);
			}
		}
		
		return result;
	}

}
